// 定义一个axios对象
const baseUrl = 'https://ouyujingcheng.com';
// const baseUrl = 'http://127.0.0.1:8080';
function checkLogin(){
  const company_id = wx.getStorageSync('company_id');
  const pages = getCurrentPages();
  const current = pages[pages.length - 1];
  if(!company_id && current.route !== "/pages/login/index"){
    wx.redirectTo({
      url: '/pages/login/index',
    })
  }
  return company_id
}
const axios = {
  get: function (url, config = {}) {
    return new Promise((resolve, reject) => {
      config.company_id=checkLogin();
      wx.request({
        url: baseUrl + url,
        method: 'GET',
        data: config || {},
        header: config.headers || {},
        success: (res) => resolve(res.data),
        fail: (err) => {
          console.log(err)
          return reject(err)
        },
      });
    });
  },
  post: function (url, data = {}, config = {}) {
    return new Promise((resolve, reject) => {
      wx.request({
        url: baseUrl + url,
        method: 'POST',
        data: data,
        header: config.headers || {},
        success: (res) => {
          if(res.statusCode != 200 && res.data.error){
            wx.showToast({
              title: res.data.error,
              icon:"error"
            })
            return reject(res.data.error)
          }
          return resolve(res.data);
        },
        fail: (err) => {
          wx.showToast({
            title: "网络错误",
            icon:"error"
          })
          return reject(err)
        },
      });
    });
  },
};
export { axios as default, baseUrl };
